package com.gitee.feizns.itrip.personal.utils.component.interceptor;

import com.gitee.feizns.itrip.personal.beans.dto.Token;
import com.gitee.feizns.itrip.personal.utils.component.annotations.TokenValidate;
import com.gitee.feizns.itrip.personal.utils.service.TokenService;
import com.gitee.feizns.itrip.personal.utils.Utils;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author feizns
 * @since 2019/1/8 0008
 */
public class TokenValidateInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(TokenValidateInterceptor.class);

    /**
     * token请求头
     */
    public static final String TOKEN_HEADER_NAME = "token";

    private TokenService tokenService;

    private Object errorInfo;

    @Setter
    @Getter
    private String contentType;

    public TokenValidateInterceptor(TokenService tokenService, Object errorInfo) {
        this.tokenService = tokenService;
        this.errorInfo = errorInfo;
    }

    public TokenValidateInterceptor(TokenService tokenService, Object errorInfo, String contentType) {
        this.tokenService = tokenService;
        this.errorInfo = errorInfo;
        this.contentType = contentType;
    }

    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ( handler instanceof HandlerMethod ) {
            HandlerMethod method = (HandlerMethod) handler;
            TokenValidate tokenValidate = method.getMethodAnnotation(TokenValidate.class);

            if ( tokenValidate == null )
                tokenValidate = method.getBeanType().getAnnotation(TokenValidate.class);

            if ( tokenValidate != null ) {
                String val = request.getHeader(TOKEN_HEADER_NAME);
                if ( val != null ) {
                    Token token = tokenService.verification(val);
                    if ( token != null ) {
                        logger.info(method.getMethod() + " => Token验证成功");
                        return true;
                    }
                }

                error(response);
                logger.info(method.getMethod() + " => 无效的Token操作");
                return false;
            }
        }
        return super.preHandle(request, response, handler);
    }

    private void error(HttpServletResponse resp) throws IOException {
        if ( contentType != null )
            resp.setContentType(contentType);

        resp.getWriter().write(Utils.toJSONString(errorInfo));
    }

}
